<?php

include('include/header.php');
//include('include/functions.php');

?>

<html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Фильмы</title>
<script src="mtools.js" language="JavaScript" type="text/javascript" charset="utf-8"></script>
<body>
<link rel="stylesheet" type="text/css" href="rating.css">


<?php

$str= "1";
$film_per_str = 20;

$genre_url = "?str=".$str;
if(isset($_GET['sort'])) $genre_url .= "&sort=".$_GET['sort'];
if(isset($_GET['seen'])) $genre_url .= "&seen=".$_GET['seen'];

$sort_url = "?str=".$str;
if(isset($_GET['genre'])) $sort_url .= "&genre=".$_GET['genre'];
if(isset($_GET['seen'])) $sort_url .= "&seen=".$_GET['seen'];

$seen_url = "?str=".$str;
if(isset($_GET['genre'])) $seen_url .= "&genre=".$_GET['genre'];
if(isset($_GET['sort'])) $seen_url .= "&sort=".$_GET['sort'];
if(isset($_GET['search_query'])) $seen_url .= "&search_query=".$_GET['search_query'];

$str_url = '';
if(isset($_GET['genre'])) $str_url .= "&genre=".$_GET['genre'];
if(isset($_GET['sort'])) $str_url .= "&sort=".$_GET['sort'];
if(isset($_GET['search_query'])) $str_url .= "&search_query=".$_GET['search_query'];
if(isset($_GET['seen'])) $str_url .= "&seen=".$_GET['seen'];

?>

<center><a href="<? echo $genre_url; ?>">Все</a> - <a href="<? echo $genre_url; ?>&genre=1">ужасы</a> - <a href="<? echo $genre_url; ?>&genre=2">фантастика</a> - <a href="<? echo $genre_url; ?>&genre=3">боевик</a> - <a href="<? echo $genre_url; ?>&genre=4">триллер</a> - <a href="<? echo $genre_url; ?>&genre=5">фэнтези</a> - <a href="<? echo $genre_url; ?>&genre=6">комедия</a> - <a href="<? echo $genre_url; ?>&genre=7">мелодрама</a> - <a href="<? echo $genre_url; ?>&genre=8">драма</a> - <a href="<? echo $genre_url; ?>&genre=10">приключения</a> - <a href="<? echo $genre_url; ?>&genre=14">мультфильм</a> - <a href="<? echo $genre_url; ?>&genre=16">криминал</a> - <a href="<? echo $genre_url; ?>&genre=22">биография</a> - <a href="<? echo $genre_url; ?>&genre=23">история</a></center>
<br>
<center><a href="<? echo $sort_url; ?>">по рейтингу Кинопоиск</a> - <a href="<? echo $sort_url; ?>&sort=local_reit">по внутрисетевому рейтингу</a> - <a href="<? echo $sort_url; ?>&sort=date" >по дате добавления</a> - <a href="<? echo $sort_url; ?>&sort=<? if($_GET['sort'] == 'year_down') echo 'year_up'; else echo "year_down"; ?>" >год издания</a></center>
<br>

<? if(isset($_REQUEST[session_name()])) { ?>

<center><a href="<? echo $seen_url; ?>">не смотрел</a> - <a href="<? echo $seen_url; ?>&seen=true" >все</a></center>
<br>

<?php
}

if($_SESSION['user'] == 'w1r0x')
{
   //Получаем список фильмов
   $films = GetFilms();
   if(count($films) > 0) echo "<center><a href=\"/add.php\">Новые фильмы: ".count($films)."</a><br></center>";
}

?>
<br>
<div align="left">
<form action="" method="get">
<input type="text" name="search_query" maxlength="30" size="15">  <input type="submit" name="submit" value="Поиск">
</form>
</div>

<div align="right"> <? if(isset($_SESSION['user'])) echo "Вы вошли как: ".$_SESSION['user']."<br><a href=\"login.php?action=quit\">Выход</a>"; else echo "<a href=\"login.php?action=login\">Войти</a><br><a href=\"register.php\">Регистрация</a>"; ?></div>

<?php

   //TODO: Кто это уже смотрел?

   //TODO: Рейтинг
      //TODO: Полуавтоматическое удаление при низком рейтинге

   //TODO: Рассылка

   $mysql = mysql_connect("localhost", "root", "kGbN85Z");
   mysql_query("USE ftp;");

   //Выборка фильмов
   if (isset($_SESSION['user'])) $sql = "SELECT *, (SELECT SUM(vote)/COUNT(*) FROM `films_raiting` WHERE `film_id` = `id` ) AS own_raiting, (SELECT COUNT(*) FROM `watched_films` WHERE `film_id` = `id` AND `user_id` = ( SELECT `id` FROM `users` WHERE `login` = '".mysql_real_escape_string($_SESSION['user'])."' )) AS watched, (SELECT vote FROM `films_raiting` WHERE `film_id` = `id` AND `user_id` = ( SELECT `id` FROM `users` WHERE `login` = '".mysql_real_escape_string($_SESSION['user'])."' )) AS my_raiting, `desc`  FROM `films` ";
   else $sql = "SELECT *, (SELECT SUM(vote)/COUNT(*) FROM `films_raiting` WHERE `film_id` = `id` ) AS own_raiting, `desc` FROM films ";

   //Определенного жанра
   if( isset($_GET['genre']) ) $sql .= " WHERE id IN ( SELECT film_id FROM film_genre WHERE genre_id = '".mysql_real_escape_string($_GET['genre'])."' )";

   if( (isset($_SESSION['user'])) && !(isset($_GET['search_query'])) && !isset($_GET['seen']) )
   {
      //Только те что не смотрел
      if( isset($_GET['genre']) ) $sql .= " AND id NOT IN ( SELECT film_id FROM watched_films WHERE user_id = ( SELECT id FROM users WHERE login =  '".mysql_real_escape_string($_SESSION['user'])."') )";
      else $sql .= " WHERE id NOT IN ( SELECT film_id FROM watched_films WHERE user_id = ( SELECT id FROM users WHERE login =  '".mysql_real_escape_string($_SESSION['user'])."') )";
   }

   //Поиск
   if(isset($_GET['search_query']))
   {
      $sql .= " WHERE";
      //Разбиваем на слова
      $sq = explode(' ',$_GET['search_query']);
      for($i=0;$i<count($sq);$i++)
      {
         if($i==0) $sql .= " LOWER(ru_name) REGEXP LOWER('".mysql_real_escape_string($sq[$i])."')"; else $sql .= " OR LOWER(ru_name) REGEXP LOWER('".mysql_real_escape_string($sq[$i])."')";
         $sql .= " OR LOWER(en_name) REGEXP LOWER('".mysql_real_escape_string($sq[$i])."')";
      }
   }

   //Сортировка
   //По дате добавления
   if( $_GET['sort'] == 'date' ) $sql .= " ORDER BY add_date DESC,kp_raiting DESC";

   //По году издания убывание
   elseif( $_GET['sort'] == 'year_down' ) $sql .= " ORDER BY year DESC,kp_raiting DESC";

   //По году издания возрастание
   elseif( $_GET['sort'] == 'year_up' ) $sql .= " ORDER BY year,kp_raiting DESC";

   //Сортировка по внутрисетевому рейтингу
   elseif( $_GET['sort'] == 'local_reit') $sql .= " ORDER BY own_raiting DESC,kp_raiting DESC";

   //Сортировка по рейтингу кинопоиска
   else $sql .= " ORDER BY kp_raiting DESC";

   //Количество записей всего
   $strs = mysql_num_rows(mysql_query($sql.";"));

   //Страничка
   if (isset($_GET['str'])) $sql .= " LIMIT ".((mysql_real_escape_string($_GET['str'])-1)*$film_per_str).", $film_per_str"; else $sql .= " LIMIT 0, $film_per_str";

   //Конец запроса
   $sql .= ";";

   //Debug
   //echo "<br><br>".$sql."<br><br>";

   //SQL запрос
   $res = mysql_query($sql) or die(mysql_error()."<br><br>".$sql);

   //Вывод результов
   while( $row = mysql_fetch_array($res) )
   {
      //Картинка
      echo "<a href=\"http://www.kinopoisk.ru/level/13/film/".$row['kp_id']."\"><IMG SRC=\"/image.php?id=$row[1]\" BORDER=\"0\" ALIGN=\"left\" WIDTH=\"120\" HEIGHT=\"175\" ></a>\n";

      //Название
      echo "<a href=\"http://www.kinopoisk.ru/level/1/film/".$row['kp_id']."\">".$row['ru_name']." (".$row['en_name'].") - ".$row['year']."</a>\n";

      //Трейлер
      if(0 && $row['trailer']) echo "&nbsp;&nbsp;&nbsp;<a href=\"/trailer\" target=\"_blank\" onClick=\"Trailer('".$row['trailer']."'); return false;\">{}<</a>\n";

      //Ссылка на закачку
      if( isset($_SESSION['user']) )
      {
          echo "&nbsp;&nbsp;&nbsp;<a href=\"ftp://";
          if(!isLocal($_SERVER['REMOTE_ADDR'])) echo $_SESSION['user'].":".$_SESSION['ftppass']."@";
          echo $_SERVER['SERVER_NAME']."/hd0/Фильмы/".$row['filename']."\">Скачать</a>";
      }
      //Сцылко на просмотрр
      if( isset($_SESSION['user']) && isLocal($_SERVER['REMOTE_ADDR']) ) echo "&nbsp;&nbsp;&nbsp;<a href=\"file:///\\\\192.168.0.110\\ftp\\hd0\\Фильмы\\".$row['filename']."\">Смотреть</a>\n";

      //Рейтинг
      //Кинопоиск
      echo "<DIV style=\"position: relative; left: 120; top: 0; height: 37px\"><div class=\"starbar\"><div class=\"outer\"><div style=\"width: ".(22*$row['kp_raiting'])."px;\" id=\"starbar\"></div></div></div></div><DIV style=\"position: relative; left: 220; top: -30; height: 0px\">&nbsp;&nbsp;Кинопоиск</div>\n";
      //IMDB
      echo "<DIV style=\"position: relative; left: 120; top: 0; height: 0px\"><div class=\"starbar\"><div class=\"outer\"><div style=\"width: ".(22*$row['imdb_raiting'])."px;\" id=\"starbar\"></div></div></div></div><DIV style=\"position: relative; left: 220; top: 5; height: 0px\">&nbsp;&nbsp;IMDB</div><br><br><br>\n";
      //Наш
      ?>
      <DIV style="position: relative; left: 120; top: -15; height: 0px">
      <div class="starbar"><div class="outer">
      <div style="width: <? echo (22*$row['own_raiting']) ?>px;" id="starbar"><div id="star<? echo $row['id']; ?>"></div></div>
      <?if(isset($_SESSION['user']))
      {?>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,10);" class="s10" title="10"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,9);" class="s9" title="9"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,8);" class="s8" title="8"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,7);" class="s7" title="7"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,6);" class="s6" title="6"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,5);" class="s5" title="5"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,4);" class="s4" title="4"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,3);" class="s3" title="3"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,2);" class="s2" title="2"></a>
      <a href="/vote" onclick="return vote(<? echo $row['id']; ?>,1);" class="s1" title="1"></a><?}?>
      </div>
      </div>
      </DIV>
      <DIV style="position: relative; left: 220; top: -10; height: 0px">&nbsp;&nbsp;Внутрисетевой<? if (isset($_SESSION['user']) && $row['my_raiting']) echo " (".$row['my_raiting'].")"; ?></div>";


      <?

      //Я это уже смотрел
      if(isset($_SESSION['user']))
      {
         //Смотрел
         if($row['watched']) echo "<br><br><span id=\"f".$row['id']."\"><a href=\"/unseen\" onclick=\"seen(".$row['id'].",0); return false;\"><( )></a></span>\n";
         //Не смотрел
         else echo "<br><br><span id=\"f".$row['id']."\"><a href=\"/seen\" onclick=\"seen(".$row['id'].",1); return false;\"><(*)></a></span>\n";
         //Поглядеть оценочки
         if($_SESSION['user'] == 'w1r0x') echo "&nbsp;&nbsp;&nbsp;<a href=\"/votes\" target=\"_blank\" onClick=\"Votes('".$row[0]."'); return false;\">!!!</a>\n";
         //Удалить
         if($_SESSION['user'] == 'w1r0x') echo "&nbsp;&nbsp;&nbsp;<a href=\"/delete\" target=\"_blank\" onClick=\"Delete('".$row[0]."'); return false;\">del</a>\n";
      }
      else echo "<br><br>";

      //Жанры
      $Genres = '';
      $sql = "SELECT (SELECT `name` FROM `genres` WHERE `id` = `genre_id`) AS genre_name FROM `film_genre` WHERE `film_id` = '".$row['id']."';";
      $gres = mysql_query($sql);
      $i=0;
      while( $grow = mysql_fetch_row($gres) )
      {
         if ( $i++ == (mysql_num_rows($gres)-1) ) $Genres .= $grow[0]; else $Genres .= $grow[0]." - ";
      }
      echo "\n<br>\n".$Genres."\n<br>";
      //echo "<br>\n<br>";

      //Описание
      echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$row['desc']."\n<br>\n<br>";

   }

   //Странички

   echo "<br><br><br><center>";

   for($i=1;$i<=ceil($strs/$film_per_str);$i++)
   {
      if($i == (ceil($strs/$film_per_str)))
      {
         if($i<>$_GET['str'])
         {
            echo "<a href=\"?str=$i".$str_url."\">".$i."</a>";
         }
         else echo $i;
      }
      else
      {
         if($i<>$_GET['str'])
         {
            echo "<a href=\"?str=$i".$str_url."\">".$i."</a>&nbsp;&nbsp;&nbsp;";
         }
         else
         {
            echo $i."&nbsp;&nbsp;&nbsp;";
         }
      }
   }
   echo "</center>";

   include('include/footer.php');

?>

</body>
</html>
